package nl.hanze.shoestring.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.*;
import java.util.List;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
import nl.hanze.shoestring.domain.Groepskorting;
import nl.hanze.shoestring.logic.Logic;
import nl.hanze.shoestring.logic.Rules;
import nl.hanze.shoestring.logic.Utils;

/**
 * Beheer Groepskorting tabel
 *
 * @author bleker
 */
public class GroepskortingPanel extends JPanel {

    Logic logic;
    JPanel pQueryInput, pRecord, pNavigation, pDbGrid;
    JLabel lblZoekSleutel, lblId, lblKortingPerc, lblKortingVan, lblKortingTot;
    JTextField txtZoekSleutel, txtId, txtKortingPerc, txtKortingVan, txtKortingTot;
    JButton butZoeken, butSave, butDelete, butEmpty;
    JTable table;
    JScrollPane scrollPaneRes;
    DefaultTableModel model;
    Groepskorting groepskortingObj = null;
    List<Groepskorting> groepkortingList;
    int heightField = 25;
    int numberOfRows = 18;

    public GroepskortingPanel(Logic logic) {
        this.logic = logic;

        table = new JTable();
        setLayout(new BorderLayout(20, 20));

        // input velden north sectie
//        pQueryInput = new JPanel();
//        pQueryInput.setLayout(null);
//        pQueryInput.setPreferredSize(new Dimension(400, 60));
//
//        lblZoekSleutel = UIHelper.createLabel(lblZoekSleutel = new JLabel(), "Zoeksleutel", 10, 10, 150, heightField, pQueryInput);
//        txtZoekSleutel = UIHelper.createTextField(txtZoekSleutel = new JTextField(), "", 170, 10, 250, heightField, pQueryInput);
//
//        butZoeken = UIHelper.createButton(butZoeken = new JButton(), "Zoeken", 430, 10, 100, heightField, pQueryInput);
//        butZoeken.addActionListener(
//                new ActionListener() {
//
//                    @Override
//                    public void actionPerformed(ActionEvent e) {
//                        System.out.println("zoek");
//                    }
//                });

        // Center sectie, database record details
        pRecord = new JPanel();
        pRecord.setLayout(null);
        pRecord.setPreferredSize(new Dimension(400, 500));
        pRecord.setBorder(BorderFactory.createLineBorder(Color.blue));

        lblId = UIHelper.createLabel(lblId = new JLabel(), "Nummer", 20, 10, 150, heightField, pRecord);
        txtId = UIHelper.createTextField(txtId = new JTextField(), "", 170, 10, 100, heightField, pRecord);

        lblKortingVan = UIHelper.createLabel(lblKortingVan = new JLabel(), "Staffel Vanaf", 20, 70, 150, heightField, pRecord);
        txtKortingVan = UIHelper.createTextField(txtKortingVan = new JTextField(), "", 170, 70, 150, heightField, pRecord);
        txtKortingVan.setToolTipText("Mag niet leeg zijn.");
        txtKortingVan.addKeyListener(new KeyAdapter() {

            @Override
            public void keyReleased(KeyEvent e) {
                if (!Rules.isNumeric(txtKortingVan.getText())) {
                    txtKortingVan.setBorder(new LineBorder(Color.red));
                } else {
                    txtKortingVan.setBorder(new LineBorder(Color.green));
                }
            }
        });

        lblKortingTot = UIHelper.createLabel(lblKortingTot = new JLabel(), "Staffel Tot", 20, 100, 150, heightField, pRecord);
        txtKortingTot = UIHelper.createTextField(txtKortingTot = new JTextField(), "", 170, 100, 150, heightField, pRecord);
        txtKortingTot.setToolTipText("Mag niet leeg zijn.");
        txtKortingTot.addKeyListener(new KeyAdapter() {

            @Override
            public void keyReleased(KeyEvent e) {
                if (!Rules.isNumeric(txtKortingTot.getText())) {
                    txtKortingTot.setBorder(new LineBorder(Color.red));
                } else {
                    txtKortingTot.setBorder(new LineBorder(Color.green));
                }
            }
        });


        lblKortingPerc = UIHelper.createLabel(lblKortingPerc = new JLabel(), "KortingPercentage", 20, 130, 150, heightField, pRecord);
        txtKortingPerc = UIHelper.createTextField(txtKortingPerc = new JTextField(), "", 170, 130, 150, heightField, pRecord);
        txtKortingPerc.setToolTipText("Moet ingesteld worden in veelvouden van 2.5.");

        txtKortingPerc.addKeyListener(new KeyAdapter() {

            @Override
            public void keyReleased(KeyEvent e) {
                if (!Rules.checkKortingPercentage(txtKortingPerc.getText())) {
                    txtKortingPerc.setBorder(new LineBorder(Color.red));
                } else {
                    txtKortingPerc.setBorder(new LineBorder(Color.green));
                }
            }
        });

        butSave = UIHelper.createButton(butSave = new JButton(), "Opslaan", 170, 220, 120, heightField, pRecord);
        butSave.addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("save");
                        if (groepskortingObj != null) {
                            updateRecord(groepskortingObj);
                        } else {
                            addRecord();
                        }
                    }
                });


        butDelete = UIHelper.createButton(butDelete = new JButton(), "Verwijderen", 350, 220, 120, heightField, pRecord);
        butDelete.addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("delete");
                        if (groepskortingObj != null) {
                            deleteRecord(groepskortingObj);
                        }
                    }
                });

        butEmpty = UIHelper.createButton(butDelete = new JButton(), "Leeg/Nieuw", 350, 10, 120, heightField, pRecord);
        butEmpty.addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        emptyAll();
                    }
                });

        // fill tab pane
        add(pRecord, BorderLayout.CENTER);
//        add(pQueryInput, BorderLayout.NORTH);
        addTable();
        emptyAll();
    }

    /**
     * Haal Groepskorting informatie uit database en toon in JTable
     */
    private void addTable() {

        // Gridcontainer
        pDbGrid = new JPanel(new BorderLayout(2, 3));

        // scroll pane eigenschappen
        scrollPaneRes = new JScrollPane(table);
        Dimension d = table.getPreferredSize();
        scrollPaneRes.setPreferredSize(new Dimension(d.width, table.getRowHeight() * numberOfRows));

        // navigatie container
        UIHelper.addNavigation(pNavigation = new JPanel(), table, scrollPaneRes, numberOfRows);

        // kolom eigenschappen - breedte
        Object[] headers = {"Nummer", "Staffel Vanaf", "Staffel Tot", "Korting%"};
        int[] breedte = {100, 200, 200, 200};

        // tablemodel en eigenschappen instellen, kolombreedte etc
        model = new DefaultTableModel(headers, 0) {

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }

            // rendering van cellen, toont checkbox en juiste datum indien datatype overeenkomstig is
            // null velden veroorzaken fout, standaard maar op String gezet....
            @Override
            public Class getColumnClass(int column) {
                try {
                    return getValueAt(0, column).getClass();
                } catch (java.lang.NullPointerException e) {
                    return String.class;
                }
            }
        };

        table.setModel(model);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        for (int i0 = 0; i0 < breedte.length; i0++) {
            table.getColumnModel().getColumn(i0).setPreferredWidth(breedte[i0]);
        }

        updateTable(true);

        // selecteer row door muisklik    
        table.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                groepskortingObj = groepkortingList.get(table.convertRowIndexToModel(table.getSelectedRow()));
                getRecord(groepskortingObj);
            }
        });

        pDbGrid.add(scrollPaneRes, BorderLayout.CENTER);
        pDbGrid.add(pNavigation, BorderLayout.SOUTH);
        add(pDbGrid, BorderLayout.SOUTH);
    }

    /*
     * Vul detailvelden met geselecteerde rowdata
     */
    private void getRecord(Groepskorting groepskortingObj) {
        txtId.setText("" + groepskortingObj.getId());
        txtId.setEditable(false);
        txtKortingVan.setText("" + groepskortingObj.getVan());
        txtKortingTot.setText("" + groepskortingObj.getTot());
        txtKortingPerc.setText("" + groepskortingObj.getKorting());
    }

    /*
     * update record
     */
    private void updateRecord(Groepskorting groepskortingObj) {

        if (!verifyInput()) {
            return;
        }

        groepskortingObj.setVan(Utils.getIntegerValueOrNull(txtKortingVan.getText()));
        groepskortingObj.setTot(Utils.getIntegerValueOrNull(txtKortingTot.getText()));
        groepskortingObj.setKorting(Utils.getFloatValueOrNull(txtKortingPerc.getText()));
        
        logic.updateGroepskorting(groepskortingObj);

        updateTable(true);
        emptyAll();

    }

    /*
     * add new record
     */
    private void addRecord() {
        if (!verifyInput()) {
            return;
        }

        groepskortingObj = new Groepskorting();
        groepskortingObj.setVan(Utils.getIntegerValueOrNull(txtKortingVan.getText()));
        groepskortingObj.setTot(Utils.getIntegerValueOrNull(txtKortingTot.getText()));
        groepskortingObj.setKorting(Utils.getFloatValueOrNull(txtKortingPerc.getText()));
        
        logic.addGroepskorting(groepskortingObj);

        updateTable(true);
        emptyAll();

    }

    /*
     * delete record
     */
    private void deleteRecord(Groepskorting groepskortingObj) {
        logic.deleteGroepskorting(groepskortingObj);
        updateTable(true);
        emptyAll();
    }

    /*
     * maak velden leeg en groepskortingObj =null
     */
    private void emptyAll() {
        txtId.setEditable(false);
        txtId.setText("");
        txtKortingVan.setText("");
        txtKortingTot.setText("");
        txtKortingPerc.setText("");
        txtKortingPerc.setBorder(new LineBorder(Color.GRAY));
        groepskortingObj = null;
    }

    private void updateTable(Boolean refresh) {
        if (refresh) {
            groepkortingList = logic.getGroepskortingList();
        }
        model.setRowCount(0);

        // data in JTable plaatsen
        for (Groepskorting groepskorting : groepkortingList) {
            Object[] o = {groepskorting.getId(),
                groepskorting.getVan(),
                groepskorting.getTot(),
                groepskorting.getKorting()};
            model.addRow(o);
        }
    }

    private boolean verifyInput() {
        boolean inputOK = true;

        if (Rules.isEmpty(txtKortingVan.getText()) || !Rules.isNumeric(txtKortingVan.getText())) {
            txtKortingVan.setBorder(new LineBorder(Color.RED));
            inputOK = false;
        } else {
            txtKortingVan.setBorder(new LineBorder(Color.gray));
        }

        if (Rules.isEmpty(txtKortingTot.getText()) || !Rules.isNumeric(txtKortingTot.getText())) {
            txtKortingTot.setBorder(new LineBorder(Color.RED));
            inputOK = false;
        } else {
            txtKortingTot.setBorder(new LineBorder(Color.gray));
        }

        if (!Rules.checkKortingPercentage(txtKortingPerc.getText())) {
            inputOK = false;
            txtKortingPerc.setBorder(new LineBorder(Color.RED));
        } else {
            txtKortingPerc.setBorder(new LineBorder(Color.gray));
        }

        return inputOK;
    }

    private boolean verifyInput(Groepskorting groepskortingObj) {
        boolean inputOK = true;

        if (groepskortingObj.getVan() >= 0) {
            txtKortingVan.setBorder(new LineBorder(Color.gray));
        } else {
            txtKortingVan.setBorder(new LineBorder(Color.RED));
            inputOK = false;
        }

        if (groepskortingObj.getTot() >= 0) {
            txtKortingTot.setBorder(new LineBorder(Color.gray));

            txtKortingTot.setBorder(new LineBorder(Color.RED));
            inputOK = false;
        } else {
        }

        if (!Rules.checkKortingPercentage(groepskortingObj)) {
            inputOK = false;
            txtKortingPerc.setBorder(new LineBorder(Color.RED));
        } else {
            txtKortingPerc.setBorder(new LineBorder(Color.gray));
        }

        return inputOK;
    }
}
